<?php

class AtomFeedParser {
    
    private $links;
    
    const KEY_HUB = "hub";
    
    public function __construct($links = array()) {
        $this->setLinks($links);
    }
    
    private function setLinks(Array $links) {
        $this->links = $links;
    }
    
    public function getLinks() {
        return $this->links;
    }
    
    public function getLinkHub() {
        return $this->getLinkWithKey(self::KEY_HUB);
    }
    
    private function getLinkWithKey($key) {
        if(is_array($this->links[$key])) {
            return $this->links[$key];
        }
        return array();
    }
    
    /**
     * 
     * @param unknown_type $rawXml
     * @return AtomFeedParser
     */
    public static function buildFromRawXML($rawXml) {
        $dom = new DOMDocument();
        if(@$dom->loadXML($rawXml)) {
            return self::buildFromDom($dom);
        }
        throw new Exception("Invalid raw XML data provided!");
    }
    
    public static function buildFromDom(DOMDocument $dom) {
        $feed_element = $dom->getElementsByTagName('feed')->item(0);
        if (!$feed_element) {
            throw new Exception("Invalid DOM object for AtomFeedParser, missing feed root");
        }
        
        $links = "";
        foreach ($feed_element->getElementsByTagName('link') as $element) {
            $rel = $element->getAttribute('rel');
            if($rel) {
                $links[$rel]['href'] =  $element->getAttribute('href');
                $links[$rel]['type'] =  $element->getAttribute('type');  
            }
        }
        
        return new AtomFeedParser($links);
    }
}